package cn.itcast.web.task;

import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.ExportExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.system.UserService;
import cn.itcast.vo.ExportResult;
import cn.itcast.web.rabbit.MailProducer;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时查询保运结果
 *    时间：每5秒查询
 */
public class ExportTask {

    @Reference
    private ExportService exportService;

    @Reference
    private ContractService contractService;

    @Autowired
    private UserService userService;

    @Autowired
    private MailProducer mailProducer;

    public void execute() {
        //1、查询所有状态=2的报运单（没有保运结果的报运单）
        ExportExample example = new ExportExample();
        ExportExample.Criteria criteria = example.createCriteria();
        criteria.andStateEqualTo(2L);
        List<Export> list = exportService.findAll(example);
        //2、循环报运单
        for (Export export : list) {
            //3、通过webclient发送请求获取响应
            WebClient webClient = WebClient.create("http://localhost:9001/ws/export/ep/" + export.getId());
            ExportResult result = webClient.get(ExportResult.class);
            //4、判断返回状态 （需要处理状态!=2的报运单）
            if(result.getState() != 2) {
                //5、调用service处理报运结果
                exportService.updateE(result);
            }
        }
    }

    //定时发送交货提醒
    public void DDAExecute() {
        //获取当天的日期并进行格式转化
        /*Date date = new Date();
        String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(date);*/
        //为了测试将日期写死为如下，需求是获取当天的日期
        String d = "2019-06-10";
        List<Contract> list = contractService.findByDate(d + "%");
        if (list != null) {
            String contractNos = "";
            for (Contract contract : list) {
                contractNos += contract.getContractNo() + ",";
            }
            contractNos = contractNos.substring(0, contractNos.length() - 1);
            List<User> users = userService.findByDegree(1);
            for (User user : users) {
                String to = user.getEmail();
                System.out.println(user.getEmail());
                String subject = "交货提醒";
                String content = "尊敬的管理员您好，今日有货物到期，需要及时交付。合同号是：" + contractNos;
                Map<String,String> map = new HashMap<>();
                map.put("to", to);
                map.put("subject", subject);
                map.put("content", content);
                mailProducer.send("user.insert",map);
            }
        }
    }

}
